package com.cheche.dn.monitor;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * Controller 调用时间监控
 * Created by cheshun on 15/11/5.
 */
@Aspect
@Order(Ordered.HIGHEST_PRECEDENCE)
@Component
public class ControllerMonitor {

    private static final Logger logger = LoggerFactory.getLogger(ControllerMonitor.class);

    @Pointcut("execution(public * com.cheche.dn.domain..*Controller.*(..))")
    public void controller() {}

    @Around("controller()")
    public Object controller(ProceedingJoinPoint pjp) throws Throwable {
        long start = System.currentTimeMillis();
        Object obj = pjp.proceed();
        long end = System.currentTimeMillis();
        long time = end - start;
        if (time > 100) {
            Signature signature = pjp.getSignature();
            MethodSignature methodSignature = (MethodSignature) signature;
            RequestMapping rm = methodSignature.getMethod().getAnnotation(RequestMapping.class);
            logger.warn("the api is so slow [{}], url=[{}, {}]", time, rm.value(), rm.method());
        }
        return obj;
    }
}
